<?php


namespace App\Game\Core;

use App\Game\Conf\GameProgress;
use App\Game\Conf\MainCmd;

class Message
{

    //推送信息给用户（不用关心用户是否重连，直接发送）
    public static function pushDataToUser($account, $data, $scmd, $code = 1)
    {
        $data = Packet::packFormat('OK', $code, $data);
        $data = Packet::packEncode($data, MainCmd::CMD_SYS, $scmd);
        $fd = getFdByAccount($account);
        if ($fd) {
            server()->push($fd, $data, WEBSOCKET_OPCODE_BINARY);
        }
    }


    //推送信息给玩家，不推送给掉线或者重连的用户
    public static function pushDataToPlayer($account, $data, $scmd, $code = 1)
    {
        $data = Packet::packFormat('OK', $code, $data);
        $data = Packet::packEncode($data, MainCmd::CMD_SYS, $scmd);
        $fd = getFdByAccount($account);
        if ($fd) {
            $room_no = getRoomNoByAccount($account);
            $plstatus = playerStatus($room_no, $account);
            if ($plstatus == GameProgress::USER_ONLINE) { //玩家在线才能发送消息
                server()->push($fd, $data, WEBSOCKET_OPCODE_BINARY);
            }
        }
    }

    //房间广播推送，默认不推送给掉线或者重连的用户 type：0=不推送掉线 1=推送掉线
    public static function broadcast($room_no, $data, $scmd, $type = 0)
    {
        ddTitle('broadcast');
        $players = Room::getRoomWait($room_no);
        dd('players', $players);
        dd('data', $data);
        if (!empty($players)) {
            $data = Packet::packFormat('OK', 1, $data);
            $data = Packet::packEncode($data, MainCmd::CMD_SYS, $scmd);

            foreach ($players as $account) {
                $is_robot = Robot::isRobot($room_no, $account);
                if ($is_robot) {
                    continue;
                }
                if (!$type) {
                    $plstatus = playerStatus($room_no, $account);
                    if ($plstatus != GameProgress::USER_ONLINE) {//玩家在线才能发送消息
                        continue;
                    }
                }
                $fd = getFdByAccount($account);
                if ($fd) {
                    server()->push($fd, $data, WEBSOCKET_OPCODE_BINARY);
                }
            }
        }
    }

    public static function forceQuit($room_no, $account)
    {
        pushForceQuitMsg($room_no, $account);
    }

}